<template>
  <div class="dc-container dc-main" v-loading="loading">
    <edit-form ref="editForm" :permission="permission" @save-finished="getList" @before-load="setLoad" @after-load="resetLoad"></edit-form>
    <el-container direction="horizontal">
      <el-aside width="200px">
        <vxe-table ref="leftTableRef" id="leftTableRef" :data="routerOptions" :tree-config="{}" @current-change="onRouterChange">
          <vxe-column field="name" title="路由" tree-node resizable min-width="180px" align="left" header-align="center" sortable show-overflow></vxe-column>
        </vxe-table>
      </el-aside>
      <el-main>
        <el-row :gutter="0" justify="start" align="top">
          <el-col :span="19">
            <query-tag ref="queryTag" v-model="queryEditObject"
              :moreParm="moreParm" :routerId="$route && $route.meta.routerId" :isConditionPanel="isConditionPanel"
              @queryTagPanel="onQueryTagPanel" @queryTagClick="onQueryTagClick" @search="onSearch"></query-tag>
          </el-col>
          <el-col :span="5">
            <div style="text-align: right">
              <el-button-group>
                <el-tooltip effect="dark" content="搜索">
                  <el-button @click="onSearch" type="primary" icon="Search"></el-button>
                </el-tooltip>
                <el-tooltip effect="dark" content="重置">
                  <el-button type="primary" icon="RefreshRight"
                    @click="isConditionPanel ? $refs.conditionPanel.reset() : $refs.queryForm.resetFields()"></el-button>
                </el-tooltip>
                <el-tooltip effect="dark" content="更多">
                  <el-button @click="onConditionPanel('query')" type="primary" icon="DArrowRight"></el-button>
                </el-tooltip>
              </el-button-group>
            </div>
          </el-col>
        </el-row>
        <condition-panel v-if="isConditionPanel" ref="conditionPanel" v-model="moreParm"
          :conditionColumns="meta.find((item) => { return item.type == 'main' }).conditionPanel"></condition-panel>
        <el-form v-if="!isConditionPanel" ref="queryForm" :model="queryData" label-width="100px">
          <el-row>
            <el-col :span="6">
              <el-form-item label="名称">
                <el-input v-model="queryData['resource_name']" :maxLength="128" placeholder="请输入名称" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="编号">
                <el-input v-model="queryData['resource_code']" :maxLength="64" placeholder="请输入编号" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="URL">
                <el-input v-model="queryData['resource_url']" :maxLength="128" placeholder="请输入URL" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="权限">
                <el-input v-model="queryData['resource_permission']" :maxLength="32" placeholder="请输入权限" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-row :gutter="0" justify="end" align="top">
          <el-button type="primary" icon="Plus" @click="onCreate" v-show="permission.add">添加</el-button>
        </el-row>
        <vxe-table ref="tableRef" :id="'tableRef_' + $route.meta.routerId"
          :data="tableData" @sort-change="onSortChange">
          <vxe-column field="name" title="名称" resizable min-width="100px" align="left" header-align="center" sortable show-overflow></vxe-column>
          <vxe-column field="code" title="编号" resizable min-width="100px" align="left" header-align="center" sortable show-overflow></vxe-column>
          <vxe-column field="url" title="URL" resizable min-width="120px" align="left" header-align="center" sortable show-overflow></vxe-column>
          <vxe-column field="permission" title="权限" resizable min-width="100px" align="left" header-align="center" sortable show-overflow></vxe-column>
          <vxe-column field="router.name" title="路由" resizable min-width="100px" align="left" header-align="center" sortable show-overflow></vxe-column>
          <vxe-column field="canPermission" title="可以授权" resizable width="80px" align="center" header-align="center" sortable>
            <template #default="scope">
              <el-tag size="small" :type="scope.row.canPermission === '1' ? 'success' : 'danger'">
                {{ scope.row.canPermission === '1' ? '是' : '否' }}
              </el-tag>
            </template>
          </vxe-column>
          <vxe-column field="isDefault" title="默认资源" resizable width="80px" align="center" header-align="center" sortable>
            <template #default="scope">
              <el-tag size="small" :type="scope.row.isDefault === '1' ? 'success' : 'info'">
                {{ scope.row.isDefault === '1' ? '是' : '否' }}
              </el-tag>
            </template>
          </vxe-column>
          <vxe-column field="isLocked" title="禁用" resizable width="60px" align="center" header-align="center" sortable>
            <template #default="scope">
              <el-tag size="small" :type="scope.row.isLocked === '1' ? 'danger' : 'success'">
                {{ scope.row.isLocked === '1' ? '是' : '否' }}
              </el-tag>
            </template>
          </vxe-column>
          <vxe-column field="createBy" title="创建者" resizable width="120px" align="center" header-align="center" show-overflow :visible="false"></vxe-column>
          <vxe-column field="createDate" title="创建时间" resizable width="160px" align="right" header-align="center" sortable show-overflow :visible="false"></vxe-column>
          <vxe-column field="updateBy" title="更新者" resizable width="120px" align="center" header-align="center" show-overflow :visible="false"></vxe-column>
          <vxe-column field="updateDate" title="更新时间" resizable width="160px" align="right" header-align="center" sortable show-overflow></vxe-column>
          <vxe-column title="操作" resizable width="160px" fixed="right" align="left" header-align="center">
            <template #header>
              <span>操作</span>
              <OperationIcon @click="onExport" type="primary" content="导出excel文件" icon-name="Download"></OperationIcon>
              <OperationIcon @click="onSetting('tableRef')" type="primary" content="自定义列" icon-name="Setting"></OperationIcon>
            </template>
            <template #default="scope">
              <OperationIcon @click="onView(scope)" type="info" v-show="permission.view" content="查看" icon-name="View"></OperationIcon>
              <OperationIcon @click="onEdit(scope)" type="primary" v-show="permission.edit" content="编辑" icon-name="Edit"></OperationIcon>
              <OperationIcon @click="onCopy(scope)" type="primary" v-show="permission.add" content="复制" icon-name="DocumentCopy"></OperationIcon>
              <OperationIcon @click="onDelete(scope)" type="danger" v-show="permission.remove" content="删除" icon-name="Delete"></OperationIcon>
            </template>
          </vxe-column>
        </vxe-table>
        <el-pagination :total="tableDataTotal" :page-size="search.limit" :current-page="tableDataPage" :page-sizes="[10, 20, 30, 40, 50, 100]"
          @size-change="onSizeChange" @current-change="onCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
          style="display: flex; justify-content: flex-end; margin-top: 10px;"></el-pagination>
      </el-main>
    </el-container>        
  </div>
</template>
<script>
import { validatenull } from '@/utils/validate'
import { listResourcePage, deleteResource } from '@/api/sys/resource'
import { listResourcePermission } from '@/api/admin/common/permission'
import EditForm from './form'
import QueryTag from '@/views/components/queryTag'
import ConditionPanel from '@/views/components/conditionPanel'
import meta from './meta'
import MainUI from '@/views/components/mainUI'
import OperationIcon from '@/components/OperationIcon'
import { treeRouter } from '@/api/sys/router'

export default {
  extends: MainUI,
  components: { EditForm, QueryTag, ConditionPanel, OperationIcon },
  data() {
    return {
      permission: { view: false, add: false, edit: false, remove: false, export: false },
      meta,
      queryData: {
        'resource_name': '',
        'resource_code': '',
        'resource_url': '',
        'resource_permission': '',
        'resource_router_id': ''
      },
      search: {
        params: [],
        columnName: '',
        order: '',
        offset: 0,
        limit: 10
      },

      tableData: [],
      tableDataPage: 1,
      tableDataTotal: 0,

      tableId: 'sys_resource',
      
      routerOptions: []
    }
  },
  computed: {},
  methods: {
    getList() {
      this.setLoad()
      /* 查询参数 和数据权限 */
      this.search.params = []
      if (this.isConditionPanel) {
        this.search.params = this.search.params.concat(this.compositeCondition())
      } else {
        if(this.queryData['resource_name']) {
          this.search.params.push({
            columnName: 'resource.name',
            queryType: 'like',
            value: this.queryData['resource_name']
          })
        }
        if(this.queryData['resource_code']) {
          this.search.params.push({
            columnName: 'resource.code',
            queryType: 'like',
            value: this.queryData['resource_code']
          })
        }
        if(this.queryData['resource_url']) {
          this.search.params.push({
            columnName: 'resource.url',
            queryType: 'like',
            value: this.queryData['resource_url']
          })
        }
        if(this.queryData['resource_permission']) {
          this.search.params.push({
            columnName: 'resource.permission',
            queryType: 'like',
            value: this.queryData['resource_permission']
          })
        }
        if(this.queryData['resource_router_id']) {
          this.search.params.push({
            columnName: 'resource.router_id',
            queryType: '=',
            value: this.queryData['resource_router_id']
          })
        }
      }
      
      // 数据权限
      this.pushDataPermissions(this.search.params, this.$route.meta.routerId, this.tableId)
      
      listResourcePage(this.search)
        .then((responseData) => {
          if (responseData.code == 100) {
            this.tableDataTotal = responseData.data.total
            this.tableData = responseData.data.rows ? responseData.data.rows : []
          } else {
            this.showMessage(responseData)
          }
          this.resetLoad()
        })
        .catch((error) => {
          this.outputError(error)
        })
    },
    onSearch() {
      if (this.isConditionPanel) {
        this.search.offset = 0
        this.tableDataPage = 1
        this.getList()
      } else {
        this.$refs['queryForm'].validate((valid) => {
          if (valid) {
            this.search.offset = 0
            this.tableDataPage = 1
            this.getList()
          } else {
            return false
          }
        })
      }
    },
    onSizeChange(val) {
      this.tableDataPage = 1
      this.search.limit = val
      this.search.offset = (this.tableDataPage - 1) * val
      this.getList()
    },
    onCurrentChange(val) {
      this.search.offset = (val - 1) * this.search.limit
      this.tableDataPage = val
      this.getList()
    },
    async pageInit() {
      this.setLoad()
      try {
        this.initOptions()
        this.search.params = []
        this.pushDataPermissions(this.search.params, this.$route.meta.routerId, this.tableId)
        let [resourceRespData, permissionRespData] = await Promise.all([
          listResourcePage(this.search),
          listResourcePermission(this.$route.meta.routerId)
        ])
        if (resourceRespData.code == 100 && permissionRespData.code == 100) {
          this.tableDataTotal = resourceRespData.data.total
          this.tableData = resourceRespData.data.rows ? resourceRespData.data.rows : []
          
          this.permission.view = permissionRespData.data.find((item) => {
            return item.permission === 'resource:read'
          })
          this.permission.export = permissionRespData.data.find((item) => {
            return item.permission === 'resource:export'
          })

          this.permission.add = permissionRespData.data.find((item) => {
            return item.permission === 'resource:create'
          })
          this.permission.edit = permissionRespData.data.find((item) => {
            return item.permission === 'resource:update'
          })
          this.permission.remove = permissionRespData.data.find((item) => {
            return item.permission === 'resource:delete'
          })
        } else {
          this.showMessage(permissionRespData.code != 100 ? permissionRespData : resourceRespData)
        }
        this.resetLoad()
      } catch (error) {
        this.outputError(error)
      }
    },
    onView(scope) {
      this.$refs.editForm.openView(scope.row.id)
    },
    onCreate(scope) {
      this.$refs.editForm.openAdd(scope ? scope.row : null)
    },
    onEdit(scope) {
      this.$refs.editForm.openEdit(scope.row.id)
    },
    onCopy(scope) {
      this.$refs.editForm.openCopy(scope.row.id)
    },
    onDelete(scope) {
      this.$confirm('确定删除吗？', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.setLoad()
          deleteResource(scope.row)
            .then((responseData) => {
              if (responseData.code == 100) {
                this.getList()
                this.showMessage({
                  type: 'success',
                  msg: '删除成功'
                })
              } else {
                this.showMessage(responseData)
              }
              this.resetLoad()
            })
            .catch((error) => {
              this.outputError(error)
            })
        })
        .catch(() => {})
    },
    onSetting(tableRef) {
      this.$refs[tableRef].triggerCustomEvent(event)
    },
    onExport() {
      this.$refs.tableRef.exportData()
    },
    onSortChange(orderby) {
      if (validatenull(orderby.prop)) {
        this.search.columnName = ''
        this.search.order = ''
      } else {
        this.search.columnName = orderby.prop
        this.search.order = orderby.order
      }
      this.getList()
    },
    onRouterChange({ newValue }) {
      this.queryData['resource_router_id'] = newValue.id
      this.$nextTick(() => {
        this.getList()
      })
    },
    initRouterOptions() {
      let search_List = { params: [] }
      
      treeRouter(search_List).then((responseData) => {
        if (responseData.code == 100) {
          this.routerOptions = responseData.data
        } else {
          this.showMessage(responseData)
        }
      })
    },
    initOptions() {
      this.initRouterOptions()
    }
  },
  watch: {
    'queryData.resource_router_id': {
      handler(newVal, oldVal) {
        if(newVal != oldVal) {
          this.queryData['resource_router_id'] = newVal
        }
      }
    }    
  },
  mounted() {
    this.pageInit()
  }
}
</script> 